<?php namespace App\Http\Controllers\Api;

use App\Contestants;
use App\Http\Controllers\Controller;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\config;
use App\Http\Services\Wechat\WechatLogin;
use App\User;
use App\UserAddress;
use App\Userinfo;
use App\UserPrize;
use App\Votes;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class VoteController extends Controller
{
    public function getContestantList(Request $request){
        $user = UserManager::isLogin($request);

        if(!$user){
            return response()->json(['level'=>'error','message'=>'请先登录！','data'=>'no_login']);
        }

        $manPlayerList  = [];
        $girlPlayerList = [];

        $manPlayers = Contestants::whereSex(1)->orderBy("id",'asc')->get();
        if(count($manPlayers) > 0){
            foreach ($manPlayers as $key=>$manPlayer){
                if($manPlayer->photo_id != 0){
                    $manPlayer->photo_url = FileManager::getImgFromOssUrl($manPlayer->photo_id);
                }else{
                    $manPlayer->photo_url = 'http://file.rzkeji.com/web/nyh5/images/3.jpg';
                }
//                $manPlayer->photo_url = 'http://file.rzkeji.com/web/nyh5/images/boy.jpg';

                $manPlayer->vote_num = $manPlayer->vote_num + 298;

                $manPlayer->rank  = $key + 1;
                array_push($manPlayerList,$manPlayer);
            }
        }

        $girlPlayers = Contestants::whereSex(0)->orderBy("id",'asc')->get();
        if(count($girlPlayers) > 0){
            foreach ($girlPlayers as $key=>$girlPlayer){
//                $girlPlayer->photo_url = FileManager::getImgFromOssUrl($girlPlayer->photo_id);
//                $girlPlayer->photo_url = 'http://file.rzkeji.com/web/nyh5/images/girl.jpg';
//                $girlPlayer->photo_url = 'http://file.rzkeji.com/web/nyh5/images/3.jpg';
                if($girlPlayer->photo_id != 0){
                    $girlPlayer->photo_url = FileManager::getImgFromOssUrl($girlPlayer->photo_id);
                }else{
                    $girlPlayer->photo_url = 'http://file.rzkeji.com/web/nyh5/images/3.jpg';
                }
                $girlPlayer->vote_num = $girlPlayer->vote_num + 298;

                $girlPlayer->rank  = $key + 1;
                array_push($girlPlayerList,$girlPlayer);
            }
        }

        $result = [
            'boy_list' => $manPlayerList,
            'girl_list'=>$girlPlayerList
        ];

        return response()->json(['level'=>'success','message'=>'获取成功！','data'=>$result]);
    }

    public function setVote(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);

        if(!$user){
            return response()->json(['level'=>'error','message'=>'请先登录！','data'=>'no_login']);
        }

        $boyIds  = $request->get('boy_ids');
        $girlIds = $request->get('girl_ids');

        if(strtotime('2019-12-14 11:00:00') < time()){
            return response()->json(['level'=>'error','message'=>'人气投票已于2019-12-14 11:00:00截止咯！','data'=>'']);
        }

        if(count($boyIds) > 0){
            $boyContestantIds = Contestants::whereSex(1)->pluck('id')->toArray();

            $userHasVote = Votes::whereUserId($user->id)->whereIn('contestants_id',$boyContestantIds)->first();
            if($userHasVote){
                return response()->json(['level'=>'error','message'=>'男子组您已经投过票了哦！','data'=>'']);
            }

            if(!is_array($boyIds))
                return response()->json(['level'=>'error','message'=>'数据格式错误！','data'=>'']);

            if(count($boyIds) > 3){
                return response()->json(['level'=>'error','message'=>'男子组最多投3票！','data'=>'']);
            }

            foreach ($boyIds as $boyId){
                $thatContestants = Contestants::whereId($boyId)->whereSex(1)->first();
                if(!$thatContestants)
                    return response()->json(['level'=>'error','message'=>'男子组存在非法数据！','data'=>'']);

                $hasVote = Votes::whereUserId($user->id)->whereContestantsId($thatContestants->id)->first();
                if($hasVote){
                    return response()->json(['level'=>'error','message'=>'男子组存在重复投票！','data'=>'']);
                }
            }
        }

        if(count($girlIds) > 0){
            $girlContestantIds = Contestants::whereSex(0)->pluck('id')->toArray();

            $userHasVote = Votes::whereUserId($user->id)->whereIn('contestants_id',$girlContestantIds)->first();
            if($userHasVote){
                return response()->json(['level'=>'error','message'=>'女子组您已经投过票了哦！','data'=>'']);
            }

            if(!is_array($girlIds))
                return response()->json(['level'=>'error','message'=>'数据格式错误！','data'=>'']);

            if(count($girlIds) > 3){
                return response()->json(['level'=>'error','message'=>'女子组最多投3票！','data'=>'']);
            }

            foreach ($girlIds as $girlId){
                $thatContestants = Contestants::whereId($girlId)->whereSex(0)->first();
                if(!$thatContestants)
                    return response()->json(['level'=>'error','message'=>'女生组存在非法数据！','data'=>'']);

                $hasVote = Votes::whereUserId($user->id)->whereContestantsId($thatContestants->id)->first();
                if($hasVote){
                    return response()->json(['level'=>'error','message'=>'女生组存在重复投票！','data'=>'']);
                }
            }
        }

        if(!is_null($boyIds) && count($boyIds) > 0)
        {
            $theIds = $boyIds;
        }elseif (!is_null($girlIds) && count($girlIds)){
            $theIds = $girlIds;
        }else{
            $theIds = [];
        }

        if(count($theIds) > 0){
            foreach ($theIds as $theId){
                $thatContestants = Contestants::whereId($theId)->first();
                if(!$thatContestants)
                    return response()->json(['level'=>'error','message'=>'非法数据！','data'=>'']);

                $newVote = new Votes();
                $newVote->contestants_id = $thatContestants->id;
                $newVote->user_id = $user->id;
                $newVote->save();

                $thatContestants->vote_num = $thatContestants->vote_num + 1;
                $thatContestants->save();
            }
        }


        return response()->json(['level'=>'success','message'=>'投票成功！','data'=>'']);

    }

    public function getRankList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);

        if(!$user){
            return response()->json(['level'=>'error','message'=>'请先登录！','data'=>'no_login']);
        }

        $manPlayerList  = [];
        $girlPlayerList = [];

        $manPlayers = Contestants::whereSex(1)->where('realname',"<>","黑马")->where('vote_num','>',0)->orderBy("vote_num",'desc')->limit(3)->get();
        if(count($manPlayers) > 0){
            foreach ($manPlayers as $key=>$manPlayer){
//                $manPlayer->photo_url = FileManager::getImgFromOssUrl($manPlayer->photo_id);
//                $manPlayer->photo_url = 'http://file.rzkeji.com/web/nyh5/images/boy.jpg';
//                $manPlayer->photo_url = 'http://file.rzkeji.com/web/nyh5/images/3.jpg';
                if($manPlayer->photo_id != 0){
                    $manPlayer->photo_url = FileManager::getImgFromOssUrl($manPlayer->photo_id);
                }else{
                    $manPlayer->photo_url = 'http://file.rzkeji.com/web/nyh5/images/3.jpg';
                }
                $manPlayer->vote_num = $manPlayer->vote_num + 298;
                $manPlayer->rank  = $key + 1;
                array_push($manPlayerList,$manPlayer);
            }
        }

        $girlPlayers = Contestants::whereSex(0)->where('realname',"<>","黑马")->where('vote_num','>',0)->orderBy("vote_num",'desc')->limit(3)->get();
        if(count($girlPlayers) > 0){
            foreach ($girlPlayers as $key=>$girlPlayer){
//                $girlPlayer->photo_url = FileManager::getImgFromOssUrl($girlPlayer->photo_id);
//                $girlPlayer->photo_url = 'http://file.rzkeji.com/web/nyh5/images/girl.jpg';
//                $girlPlayer->photo_url = 'http://file.rzkeji.com/web/nyh5/images/3.jpg';
                if($girlPlayer->photo_id != 0){
                    $girlPlayer->photo_url = FileManager::getImgFromOssUrl($girlPlayer->photo_id);
                }else{
                    $girlPlayer->photo_url = 'http://file.rzkeji.com/web/nyh5/images/3.jpg';
                }

                $girlPlayer->vote_num = $girlPlayer->vote_num + 298;
                $girlPlayer->rank  = $key + 1;
                array_push($girlPlayerList,$girlPlayer);
            }
        }

        $result = [
            'boy_list' => $manPlayerList,
            'girl_list'=>$girlPlayerList
        ];

        return response()->json(['level'=>'success','message'=>'获取成功！','data'=>$result]);
    }

    public function getMyVotes(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);

        if(!$user){
            return response()->json(['level'=>'error','message'=>'请先登录！','data'=>'no_login']);
        }

        $manIdList  = [];
        $girlIdList = [];

        $myVotes = Votes::whereUserId($user->id)->orderBy('contestants_id','asc')->get();
        if(count($myVotes) > 0){
            foreach ($myVotes as $myVote){
                /** @var Votes $myVote */
                $thatContestants = Contestants::whereId($myVote->contestants_id)->first();
                if($thatContestants){
                    if($thatContestants->sex == 1){
                        array_push($manIdList,$thatContestants->id);
                    }else{
                        if($thatContestants->id > 11){
                            $thatId = $thatContestants->id - 11;
                        }else{
                            $thatId = 0;
                        }
                        if($thatId > 0)
                            array_push($girlIdList,$thatId);
                    }
                }
            }
        }

        $result = [
            'boy_ids' => $manIdList,
            'girl_ids'=>$girlIdList
        ];

        return response()->json(['level'=>'success','message'=>'获取成功！','data'=>$result]);
    }

    public function getMyPrize(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);

        if(!$user){
            return response()->json(['level'=>'error','message'=>'请先登录！','data'=>'no_login']);
        }

        if(strtotime('2019-12-14 11:00:00') > time()){
            return response()->json(['level'=>'error','message'=>'抽奖将于2019-12-14 11:00:00进行，敬请期待！','data'=>'']);
        }

        //hot lucky count
        $myPrizes = UserPrize::whereUserId($user->id)->get();
        if(count($myPrizes) == 0){
            return response()->json(['level'=>'success','message'=>'很遗憾，未获奖！','data'=>'no_prize']);
        }

        $result = [];
        foreach ($myPrizes as $myPrize){
            switch ($myPrize->prize_type){
                case 'hot':
                    array_push($result,'南粤古驿道网“人气王”幸运星！');
                    break;
                case 'lucky':
                    array_push($result,'南粤古驿道网“定向王”幸运星！');
                    break;
                case 'count':
                    array_push($result,'南粤古驿道网“神算子”！');
                    break;
            }
        }

        return response()->json(['level'=>'success','message'=>'恭喜您成为','data'=>$result]);
    }

    public function setUserPhone(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);

        if(!$user){
            return response()->json(['level'=>'error','message'=>'请先登录！','data'=>'no_login']);
        }

        $phone       = $request->get('phone');
        $realname    = $request->get('realname');
        $addressInfo = $request->get('address');
        $type        = $request->get('get_type');

        $myPrizes = UserPrize::whereUserId($user->id)->get();
        if(count($myPrizes) == 0){
            return response()->json(['level'=>'success','message'=>'很遗憾，您未中奖，无需提交资料！','data'=>'no_prize']);
        }

        $thatUserAddress = UserAddress::whereUserId($user->id)->first();
        if($thatUserAddress){
            if(is_null($thatUserAddress->phone) && is_null($phone)){
                return response()->json(['level'=>'error','message'=>'请填写手机号！','data'=>'']);
            }elseif(!is_null($phone)){
                $thatUserAddress->phone = $phone;
            }

            $thatUserInfo = Userinfo::whereUserId($user->id)->first();
            if($thatUserInfo){
                $thatUserInfo->realname = $realname;
                $thatUserInfo->save();
            }

            $thatUserAddress->address_info = $addressInfo;
            $thatUserAddress->get_type     = $type;
            $thatUserAddress->save();
        }else{
            if(is_null($phone)){
                return response()->json(['level'=>'error','message'=>'请填写手机号，不然领不到奖品哦！','data'=>'']);
            }

            $thatUserInfo = Userinfo::whereUserId($user->id)->first();
            if($thatUserInfo){
                $thatUserInfo->realname = $realname;
                $thatUserInfo->save();
            }

            $thatUserAddress = new UserAddress();
            $thatUserAddress->user_id = $user->id;
            $thatUserAddress->phone = $phone;
            $thatUserAddress->address_info = $addressInfo;
            $thatUserAddress->get_type     = $type;
            $thatUserAddress->save();
        }

        return response()->json(['level'=>'success','message'=>'提交成功，敬请期待奖品的到来！','data'=>$thatUserAddress]);
    }

    public function setLuckUser(Request $request){

        $userVotes = Votes::groupBy('user_id')->pluck('user_id')->toArray();

        $randKeys = array_rand($userVotes,50);

        foreach ($randKeys as $randKey){
            $hasUserPrize = UserPrize::whereUserId($userVotes[$randKey])->wherePrizeType('lucky')->first();
            if(!$hasUserPrize){
                $newUserPrize = new UserPrize();
                $newUserPrize->user_id = $userVotes[$randKey];
                $newUserPrize->prize_type = 'lucky';
                $newUserPrize->save();
            }
        }

        echo 'complete';
    }

    public function setHotUser(Request $request){
        $userVotes = Votes::whereIn('contestants_id',[3,14])->groupBy('user_id')->pluck('user_id')->toArray();

        $randKeys = array_rand($userVotes,50);

        foreach ($randKeys as $randKey){
            $hasUserPrize = UserPrize::whereUserId($userVotes[$randKey])->wherePrizeType('hot')->first();
            if(!$hasUserPrize){
                $newUserPrize = new UserPrize();
                $newUserPrize->user_id = $userVotes[$randKey];
                $newUserPrize->prize_type = 'hot';
                $newUserPrize->save();
            }
        }

        echo 'complete';
    }

    public function setCountUser(Request $request){
        $userVotes = Votes::whereIn('contestants_id',[11,12,22])->groupBy('user_id')->pluck('user_id')->toArray();

        $randKeys = array_rand($userVotes,50);

        foreach ($randKeys as $randKey){
            $hasUserPrize = UserPrize::whereUserId($userVotes[$randKey])->wherePrizeType('hot')->first();
            if(!$hasUserPrize){
                $newUserPrize = new UserPrize();
                $newUserPrize->user_id = $userVotes[$randKey];
                $newUserPrize->prize_type = 'hot';
                $newUserPrize->save();
            }
        }

        echo 'complete';
    }
}